package cn.geoportal.benoserver.controller;

import cn.geoportal.benoserver.config.RabbitMqConfig;
import cn.geoportal.benoserver.entity.ConvertTask;
import cn.geoportal.benoserver.entity.ConvertTaskType;
import cn.geoportal.benoserver.entity.common.PageResult;
import cn.geoportal.benoserver.entity.common.RespBean;
import cn.geoportal.benoserver.entity.vo.converttask.ConvertTaskAdd;
import cn.geoportal.benoserver.entity.vo.converttask.ConvertTaskGet;
import cn.geoportal.benoserver.entity.vo.converttask.ConvertTaskSend;
import cn.geoportal.benoserver.service.ConvertTaskService;
import cn.geoportal.benoserver.service.ConvertTaskTypeService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @ProjectName: gmo
 * @Package: cn.geoportal.benoserver.controller
 * @ClassName: ConvertTaskController
 * @Author: chiangbt@geoportal.cn
 * @Description: 转换任务路由
 * @Date: 2021/10/10 21:26
 */
@Api(tags = "1.转换任务")
@ApiSupport(order = 302)
@RestController
@RequestMapping("/api/converttask")
public class ConvertTaskController {

    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private ConvertTaskService convertTaskService;
    @Autowired
    private ConvertTaskTypeService convertTaskTypeService;

    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "ConvertTask表")
    @ApiImplicitParams({
            @ApiImplicitParam(name="pageNo", value = "当前页号", required = true, example = "1"),
            @ApiImplicitParam(name="pageSize", value = "批次数量", required = true, example = "15"),
            @ApiImplicitParam(name = "query",value = "名称", required = false, example = ""),
            @ApiImplicitParam(name = "type",value = "转换类型", required = false, example = "")
    })
    @RequestMapping(value="/", method = RequestMethod.GET)
    public RespBean list(@RequestParam(value = "pageNo", defaultValue = "1") Integer pageNo,
                         @RequestParam(value = "pageSize", defaultValue = "3") Integer pageSize,
                         @RequestParam(value="query", defaultValue = "") String query,
                         @RequestParam(value="type", defaultValue = "-1") Integer type){
        QueryWrapper<ConvertTask> wrapper = new QueryWrapper<>();
        if(type == -1) {
            System.out.println("a");
            wrapper.like("a.name", query.toLowerCase()).or().like("a.name", query.toUpperCase())
                    .or().like("a.description", query.toLowerCase()).or().like("a.description", query.toUpperCase());
        }else{
            System.out.println("b");
            wrapper.eq("a.typeid", type).and(Wrapper -> Wrapper.like("a.name", query.toLowerCase()).or().like("a.name", query.toUpperCase())
                    .or().like("a.description", query.toLowerCase()).or().like("a.description", query.toUpperCase()));
        }
        Page<ConvertTask> ipage = new Page<>(pageNo, pageSize);
        try{
            IPage<ConvertTask> dt = convertTaskService.queryConvertTaskPage(ipage, wrapper);
            dt.getRecords().forEach(e -> {
                String status = e.getStatus();
                if("0".equals(status)){
                    e.setStatusName("未转换");
                }else if("1".equals(status)){
                    e.setStatusName("转换中");
                }else if("2".equals(status)){
                    e.setStatusName("转换成功");
                }else if("3".equals(status)){
                    e.setStatusName("转换失败");
                }
            });
            PageResult<?> pageResult = new PageResult<ConvertTask>(dt.getCurrent(), dt.getSize(), dt.getTotal(), dt.getRecords());
            return RespBean.success("获取成功", pageResult);
        }catch(Exception e){
            return RespBean.error("无数据");
        }
    }

    @ApiOperationSupport(order = 2)
    @ApiOperation(value = "添加ConvertTask")
    @PostMapping(value = "", consumes = "application/json", produces = "application/json")
    public RespBean add(@RequestBody ConvertTaskAdd convertTaskAdd){
        try{
            QueryWrapper< ConvertTask> wapper = new QueryWrapper();
            wapper.eq("name",convertTaskAdd.getName()).or().eq("source",convertTaskAdd.getSource());
            int count = convertTaskService.count(wapper);
            if(count>0){
                return RespBean.error("任务名称或源文件在任务中已存在，不可重复添加");
            }
            convertTaskAdd.setStatus("0");
            int result = convertTaskService.add(convertTaskAdd);
            if(0 == result){
                return RespBean.error("添加的数据重复");
            }

            ConvertTaskType convertTaskType = convertTaskTypeService.findById(convertTaskAdd.getTypeid());
            ConvertTaskSend convertTaskSend = new ConvertTaskSend(result, convertTaskAdd.getSource(),
                    convertTaskAdd.getTarget(), convertTaskAdd.getEpsg(),
                    convertTaskAdd.getCenter(), convertTaskType.getName());
            rabbitTemplate.convertAndSend(RabbitMqConfig.EXCHANGE_NAME, RabbitMqConfig.BINDING_KEY_2, convertTaskSend);
            return RespBean.success("添加成功", result);
        }catch (Exception exp){
            System.out.println(exp.getMessage());
            return RespBean.error("添加不成功");
        }
    }

    @ApiOperationSupport(order = 3)
    @ApiOperation(value = "获取指定id的ConvertTask")
    @GetMapping(value = "/{id}", produces = "application/json")
    public RespBean getById(@PathVariable(value="id") Integer id){
        try{
            ConvertTaskGet convertask = convertTaskService.getConvertTaskById(id);
            if(null == convertask){
                return RespBean.error("记录不存在");
            }
            return RespBean.success( "获取成功", convertask);
        }catch (Exception exp){
            return RespBean.error("获取不成功");
        }
    }

    @ApiOperationSupport(order = 4)
    @ApiOperation(value = "更新指定id对象")
    @PatchMapping(value = "/{id}", produces = "application/json")
    public RespBean update(@PathVariable(value="id") Integer id, @RequestBody ConvertTask convertTask){
        try{
            convertTask.setId(id);
            int result = convertTaskService.updateConvertTask(convertTask);
            if(0 == result){
                return RespBean.error("指定更新的数据不存在");
            }
            if(-1 == result){
                return RespBean.error("指定更新的记录与已有记录的name值重复");
            }
            return RespBean.success("更新成功", result);
        }catch (Exception exp){
            return RespBean.error("更新不成功");
        }
    }

    @ApiOperationSupport(order = 5)
    @ApiOperation(value = "删除指定id对象")
    @DeleteMapping(value = "/{id}", produces = "application/json")
    public RespBean delete(@PathVariable(value="id") Integer id){
        try{
            int result = convertTaskService.deleteConvertTask(id);
            if(0 == result){
                return RespBean.error("需要删除的数据不存在");
            }
            return RespBean.success("删除成功", result);
        }catch (Exception exp){
            return RespBean.error("删除不成功");
        }
    }
}
